<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>订单调度</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-spin :spinning="spinning">
      <div class="pageTabsWhole" style="margin-top:24px;">
        <a-tabs
          default-active-key
          :activeKey="activeKey"
          :animated="false"
          :tabBarStyle="{margin:0}"
          :tabBarGutter="16"
          class="table_tab"
          @change="onChangeStatus"
        >
          <a-tab-pane key tab="全部"></a-tab-pane>
          <a-tab-pane :key="1" :tab="`待接单(${listCount.waitReceiveCount||'0'})`"></a-tab-pane>
          <a-tab-pane :key="2" :tab="`待派单(${listCount.waitDistributeCount||'0'})`"></a-tab-pane>
          <a-tab-pane :key="3" :tab="`司机待接单(${listCount.driverWaitGetCount||'0'})`"></a-tab-pane>
          <a-tab-pane :key="4" :tab="`司机待出发(${listCount.driverWaitGoCount||'0'})`"></a-tab-pane>
          <a-tab-pane :key="5" :tab="`运输中(${listCount.transitCount||'0'})`"></a-tab-pane>
          <a-tab-pane :key="6" tab="已完成"></a-tab-pane>
          <a-tab-pane :key="7" tab="已结算"></a-tab-pane>
          <!-- <a-tab-pane :key="8" tab="已作废"></a-tab-pane> -->
        </a-tabs>
      </div>

      <div class="pageContentWhole">
        <a-row>
          <a-col :span="24">
            <a-form layout="inline">
              <a-form-item label="订单类型">
                <a-select v-model="searchForm.orderType" class="selectInputWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option v-for="v in OrderOptions" :key="v.key">{{v.title}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="业务归属">
                <a-select v-model="searchForm.belongCompany" class="selectWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option key="JIA_HUA">佳华业务</a-select-option>
                  <a-select-option key="JIA_TE">自主业务</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="客户名称">
                <a-input v-model="searchForm.custName" />
              </a-form-item>
              <a-form-item label="海船公司">
                <a-input v-model="searchForm.seagoingShipCompanyName" />
              </a-form-item>
              <a-form-item label="是否加急">
                <a-select v-model="searchForm.isUrgent" class="selectWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option :key="1">是</a-select-option>
                  <a-select-option :key="0">否</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="货品名称">
                <a-input v-model="searchForm.goodsName" />
              </a-form-item>
              <a-form-item label="公司编号/运单号/箱号/封号">
                <a-input v-model="searchForm.word" />
                <!-- <a-input-group compact>
                  <a-select
                    v-model="searchForm.typeIndex"
                    @change="onChangeTypeOptions"
                    class="selectWidth"
                  >
                    <a-select-option v-for="v in typeOptions" :key="v.key">{{v.title}}</a-select-option>
                  </a-select>
                  <a-input
                    style="width: 200px"
                    @change="onNameChange"
                    v-model="searchForm.typexName"
                  />
                </a-input-group>-->
              </a-form-item>
              <a-form-item label="箱号">
                <a-input v-model="searchForm.containerNo" />
              </a-form-item>
              <a-form-item v-if="searchForm.status === 1" label="放货状态">
                <a-select v-model="searchForm.releaseStatus" class="selectWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option :key="2">已放货</a-select-option>
                  <a-select-option :key="1">未放货</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item v-if="searchForm.status === 1" label="驳船船名/航次">
                <a-input v-model="searchForm.shipNameAndVoyage" />
              </a-form-item>
              <a-form-item label="起运港">
                <a-input v-model="searchForm.startPortName" />
              </a-form-item>
              <a-form-item label="目的港">
                <a-input v-model="searchForm.endPortName" />
              </a-form-item>
              <!-- <a-form-item label="发货地址"> -->
              <a-form-item label="地址">
                <a-input v-model="searchForm.address" />
              </a-form-item>
              <a-form-item v-if="searchForm.status !== 6 && searchForm.status !== 7" label="送达日期">
                <a-range-picker
                  :value="[searchForm.arriveTime1, searchForm.arriveTime2]"
                  @change="onDateChange0"
                >
                  <a-icon slot="suffixIcon" type="calendar" />
                </a-range-picker>
              </a-form-item>
              <a-form-item
                v-if="!searchForm.status || searchForm.status === 6 || searchForm.status === 7"
              >
                <a-input-group compact>
                  <a-select
                    v-model="searchForm.datexName"
                    @change="onChangeDateOptions"
                    class="selectWidth"
                  >
                    <a-select-option :key="1">调度接单日期</a-select-option>
                    <a-select-option
                      v-if="searchForm.status === 6 || searchForm.status === 7"
                      :key="2"
                    >预计送达日期</a-select-option>
                    <a-select-option :key="3">完成订单日期</a-select-option>
                  </a-select>
                  <a-range-picker :value="time" @change="onDateChange">
                    <a-icon slot="suffixIcon" type="calendar" />
                  </a-range-picker>
                </a-input-group>
              </a-form-item>
              <a-form-item v-if="searchForm.status !== 1 && searchForm.status !== 2" label="车辆类型">
                <a-select v-model="searchForm.isSelfOperation" class="selectWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option v-for="v in SelfOperationOptions" :key="v.key">{{v.title}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item v-if="searchForm.status !== 1 && searchForm.status !== 2" label="车辆">
                <a-input v-model="searchForm.truckNumber" placeholder="牵引车/挂车车牌号" />
              </a-form-item>
              <a-form-item v-if="searchForm.status !== 1 && searchForm.status !== 2" label="司机">
                <a-input v-model="searchForm.driver" placeholder="司机姓名、手机号码" />
              </a-form-item>
              <a-form-item v-if="searchForm.status === 5" label="流程结点">
                <a-select v-model="searchForm.flowType" class="selectWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option v-for="v in flowTypes" :key="v.key">{{v.title}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item v-if="searchForm.status === 6" label="完成类型">
                <a-select v-model="searchForm.opeType" class="selectWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option v-for="v in opeTypes" :key="v.key">{{v.title}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item v-if="searchForm.status === 6" label="费用状态">
                <a-select v-model="searchForm.isCostRecorded" class="selectWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option v-for="v in costTypes" :key="v.key">{{v.title}}</a-select-option>
                </a-select>
              </a-form-item>

              <!-- 排序 -->
              <template v-if="searchForm.status === 1">
                <br />
                <a-form-item label="排序">
                  <a-select v-model="value1" class="selectWidth">
                    <a-select-option :key="0">操作派单时间</a-select-option>
                    <a-select-option :key="2">送达时间</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item>
                  <a-radio-group v-model="value2">
                    <a-radio :value="1">倒序（最新的数据在最上面）</a-radio>
                    <a-radio :value="2">正序（最新的数据在最下面）</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item label="加急置顶">
                  <a-radio-group v-model="value3">
                    <a-radio :value="1">是</a-radio>
                    <a-radio :value="0">否</a-radio>
                  </a-radio-group>
                </a-form-item>
              </template>
              <template v-if="searchForm.status === 6">
                <br />
                <a-form-item label="排序">订单完成时间</a-form-item>
                <a-form-item>
                  <a-radio-group v-model="value4">
                    <a-radio value>倒序（最新的数据在最上面）</a-radio>
                    <a-radio :value="5">正序（最新的数据在最下面）</a-radio>
                  </a-radio-group>
                </a-form-item>
              </template>

              <a-form-item>
                <a-button type="primary" @click="handleSubmit1">查询</a-button>
              </a-form-item>

              <a-form-item v-if="searchForm.status === 1 || searchForm.status === 2">
                <a-button type="primary" @click="checkBoxCheck">全选</a-button>
              </a-form-item>
              <a-form-item v-if="searchForm.status === 1">
                <a-button type="primary" @click="batchReceiveTruckOrder">批量接单</a-button>
              </a-form-item>
              <a-form-item v-if="searchForm.status === 2">
                <a-button type="primary" @click="batchAssignTruckOrder">批量指派</a-button>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
      </div>

      <div v-show="needCount > 0" style="margin: 0 24px;">
        <a-alert type="warning">
          <template slot="message">
            <p style="color: grey; margin: 0;">
              <a-icon type="info-circle" theme="twoTone" twoToneColor="#f3cd52" />
              您有 {{needCount}} 笔新订单需要接单，
              <a type="link" @click="() => {this.onChangeStatus(1)}">点击查看</a>并接单
            </p>
          </template>
        </a-alert>
      </div>

      <!-- 订单列表 -->
      <a-row class="orderItem ordertem_de ordertem_d78">
        <a-col :span="24">
          <!-- <a-spin :spinning="spinning"> -->
          <template v-if="tableData.length > 0">
            <a-checkbox-group :value="checkBox.checked">
              <div v-for="(item, index) in tableData" :key="index" class="orderList">
                <a-card size="small">
                  <template slot="title">
                    <a-checkbox
                      v-if="searchForm.status === 1 || searchForm.status === 2"
                      :value="item.orderTruckId"
                      @change="onChangeCheck"
                      class="checkBoxStyle"
                    ></a-checkbox>
                    <a-descriptions class="titleCard" style="padding-left:24px;">
                      <a-descriptions-item label="公司编号">{{item.truckOrderCode||'--'}}</a-descriptions-item>
                      <a-descriptions-item label="运单号">{{item.seagoingShipOrderCode||'--'}}</a-descriptions-item>
                      <a-descriptions-item
                        label="驳船船名航次"
                      >{{item.shipName||'--'}}/{{item.shipVoyage||'--'}}</a-descriptions-item>
                    </a-descriptions>
                  </template>
                  <template slot="extra" style="padding-right:24px;">
                    <div class="orderTags">
                      <a-tag v-if="item.isUrgent===1" color="red" class="jia">加急</a-tag>
                      <a-tag
                        v-if="item.dispatchCount > 1 && item.status === 3"
                        color="orange"
                        class="jia"
                      >抢单中</a-tag>
                      <a-tag v-if="item.belongCompany==='JIA_HUA'" class="ywu">佳华业务</a-tag>
                      <a-tag v-if="item.belongCompany==='JIA_TE'" class="ywu">自主业务</a-tag>
                    </div>
                  </template>
                  <div class="order_detail">
                    <a-descriptions :column="4" size="small">
                      <a-descriptions-item label="客户名称">{{item.custName}}</a-descriptions-item>
                      <a-descriptions-item label="箱号">
                        {{item.containerNo || '--'}}
                        {{item.holderName ? `(${item.holderName})` : ''}}
                      </a-descriptions-item>
                      <a-descriptions-item v-if="item.belongCompany==='JIA_HUA'" label="起运/目的港">
                        {{item.startPortName||'--'}}
                        <a-tag
                          v-if="isExportOrder(item.orderType)"
                          color="blue"
                        >{{getAddressType(item, item.startPortId)}}</a-tag>
                        ~ {{item.endPortName||'--'}}
                        <a-tag
                          v-if="isImportOrder(item.orderType)"
                          color="blue"
                        >{{getAddressType(item, item.endPortId)}}</a-tag>
                      </a-descriptions-item>
                      <a-descriptions-item
                        v-if="item.belongCompany==='JIA_TE'"
                        :label="addressInfo(item.addressList, 1).opeType"
                      >
                        <a-tooltip placement="topLeft">
                          <template slot="title">
                            <span>{{addressInfo(item.addressList, 1).addressAll}}</span>
                            <small
                              class="copyBtn"
                              v-clipboard:copy="addressInfo(item.addressList, 1).addressAll"
                              v-clipboard:success="onCopy"
                            >复制地址</small>
                          </template>
                          {{addressInfo(item.addressList, 1).addressAll}}
                        </a-tooltip>
                      </a-descriptions-item>
                    </a-descriptions>

                    <a-descriptions :column="4" size="small">
                      <a-descriptions-item label="海船公司">{{item.seagoingShipCompanyName||'--'}}</a-descriptions-item>
                      <a-descriptions-item label="封号">{{item.containerSealNo || '--'}}</a-descriptions-item>
                      <a-descriptions-item v-if="item.belongCompany==='JIA_HUA'" label="发货地址">
                        <span class="addressMain">
                          <a-tooltip placement="topLeft">
                            <template slot="title">
                              <span>{{item.consignorProvince||'--'}}{{item.consignorCity}}{{item.consignorArea}}{{item.consignorAddress}}</span>
                              <small
                                class="copyBtn"
                                v-clipboard:copy="`${item.consignorProvince||'--'}${item.consignorCity}${item.consignorArea}${item.consignorAddress}`"
                                v-clipboard:success="onCopy"
                              >复制地址</small>
                            </template>
                            {{item.consignorProvince||'--'}}{{item.consignorCity}}{{item.consignorArea}}{{item.consignorAddress}}
                          </a-tooltip>
                        </span>
                        <a
                          v-if="isExportOrder(item.orderType)&&item.addressList.filter(v => v.addressType === 2).length > 1"
                          @click="gotoOrderDetail(item.orderTruckId)"
                        >更多地址...</a>
                        <a-tag
                          v-if="isExportOrder(item.orderType)"
                          color="blue"
                        >{{getAddressType(item, item.startPortId, 2)}}</a-tag>
                      </a-descriptions-item>
                      <a-descriptions-item
                        v-if="item.belongCompany==='JIA_TE'"
                        :label="addressInfo(item.addressList, 1).opeType ? '联系人' : ''"
                      >
                        <p
                          style="margin:0"
                        >{{addressInfo(item.addressList, 1).linkMan}} {{addressInfo(item.addressList, 1).linkManPhone}}</p>
                      </a-descriptions-item>
                    </a-descriptions>

                    <a-descriptions :column="4" size="small">
                      <a-descriptions-item label="订单类型">{{orderTypeStr(item.orderType)}}</a-descriptions-item>
                      <a-descriptions-item label="要求送达">{{item.requiredArriveTime || '--'}}</a-descriptions-item>
                      <a-descriptions-item
                        v-if="item.belongCompany==='JIA_HUA'"
                        label="发货人"
                      >{{item.consignor||'--'}} {{item.consignorPhone}}</a-descriptions-item>
                      <a-descriptions-item
                        v-if="item.belongCompany==='JIA_TE'"
                        :label="addressInfo(item.addressList, 2).opeType"
                      >
                        <a-tooltip placement="topLeft">
                          <template slot="title">
                            <span>{{addressInfo(item.addressList, 2).addressAll}}</span>
                            <small
                              class="copyBtn"
                              v-clipboard:copy="addressInfo(item.addressList, 2).addressAll"
                              v-clipboard:success="onCopy"
                            >复制地址</small>
                          </template>
                          {{addressInfo(item.addressList, 2).addressAll}}
                        </a-tooltip>
                      </a-descriptions-item>
                    </a-descriptions>

                    <a-descriptions :column="4" size="small">
                      <a-descriptions-item label="货品名称">{{item.goodsName}}</a-descriptions-item>
                      <a-descriptions-item label="运送车辆">{{item.truckNumber||'--'}}</a-descriptions-item>
                      <a-descriptions-item v-if="item.belongCompany==='JIA_HUA'" label="收货地址">
                        <span class="addressMain">
                          <a-tooltip placement="topLeft">
                            <template slot="title">
                              <span>{{item.consigneeProvince||'--'}}{{item.consigneeCity}}{{item.consigneeArea}}{{item.consigneeAddress}}</span>
                              <small
                                class="copyBtn"
                                v-clipboard:copy="`${item.consigneeProvince||'--'}${item.consigneeCity}${item.consigneeArea}${item.consigneeAddress}`"
                                v-clipboard:success="onCopy"
                              >复制地址</small>
                            </template>
                            {{item.consigneeProvince||'--'}}{{item.consigneeCity}}{{item.consigneeArea}}{{item.consigneeAddress}}
                          </a-tooltip>
                        </span>
                        <a
                          v-if="isImportOrder(item.orderType)&&item.addressList.filter(v => v.addressType === 2).length > 1"
                          @click="gotoOrderDetail(item.orderTruckId)"
                        >更多地址...</a>
                        <a-tag
                          v-if="isImportOrder(item.orderType)"
                          color="blue"
                        >{{getAddressType(item, item.endPortId, 2)}}</a-tag>
                      </a-descriptions-item>
                      <a-descriptions-item
                        v-if="item.belongCompany==='JIA_TE'"
                        :label="addressInfo(item.addressList, 2).opeType ? '联系人' : ''"
                      >
                        <p style="margin:0">
                          {{addressInfo(item.addressList, 2).linkMan}} {{addressInfo(item.addressList, 2).linkManPhone}}
                          <a
                            v-if="item.addressList.length > 2"
                            @click="gotoOrderDetail(item.orderTruckId)"
                          >更多门点...</a>
                        </p>
                      </a-descriptions-item>
                    </a-descriptions>

                    <a-descriptions :column="4" size="small">
                      <a-descriptions-item
                        label="箱型箱量"
                      >{{item.containerType}}*{{item.containerNum||'1'}}</a-descriptions-item>
                      <a-descriptions-item
                        label="运送司机"
                      >{{item.driverName || '--'}} {{item.driverPhone}}</a-descriptions-item>
                      <a-descriptions-item
                        v-if="item.belongCompany==='JIA_HUA'"
                        label="收货人"
                      >{{item.consignee}} {{item.consigneePhone}}</a-descriptions-item>
                    </a-descriptions>

                    <a-descriptions :column="4" size="small" class="optRemarkClass">
                      <a-descriptions-item label="操作备注">
                        <a-tooltip placement="topLeft">
                          <template slot="title">
                            <span>{{item.handlerRemark||'--'}}</span>
                            <small
                              class="copyBtn"
                              v-show="item.handlerRemark"
                              v-clipboard:copy="item.handlerRemark"
                              v-clipboard:success="onCopy"
                            >复制</small>
                          </template>
                          {{item.handlerRemark||'--'}}
                        </a-tooltip>
                      </a-descriptions-item>
                    </a-descriptions>
                  </div>
                </a-card>
                <a-card size="small" style="border-top:none" class="order_czuo">
                  <template slot="title">
                    <div class="extraInfo" style="width: 120px">
                      <img src="../../../../static/images/order_zt1.png" />
                      {{statusStr[item.status]}}
                    </div>
                    <div class="extraInfo">
                      <img src="../../../../static/images/order_start.png" />
                      {{opeTypeStr(item.opeType, item.emptyOrHeavy)}}
                      <span
                        class="xdan_time"
                      >（{{item.flowTime}}）</span>
                    </div>
                    <div
                      class="extraInfo"
                      v-if="item.isCostRecorded === 1 && (item.status === 6 || item.status === 7)"
                    >
                      <img src="../../../../static/images/feid1.png" /> 费用已录完
                      <span class="xdan_time">（{{item.costRecordedTime}}）</span>
                    </div>
                    <div class="extraInfo">
                      <template v-if="item.status === 1">
                        <span v-if="item.releaseStatus===1">
                          <img
                            src="../../../../static/images/order_zt10.png"
                            style=" margin-right:3px;"
                          />扣货
                        </span>
                        <span v-else-if="item.releaseStatus===2">
                          <img
                            src="../../../../static/images/order_zt11.png"
                            style=" margin-right:3px;"
                          />可放货
                        </span>
                      </template>
                      <template v-if="item.isShipAnomalous === 1">
                        <div>
                          订单已被佳华异常结束
                          <span class="xdan_time">（{{item.shipCompleteTime}}）</span>
                        </div>
                      </template>
                    </div>
                  </template>
                  <template slot="extra">
                    <span style="color: red;">
                      总应收：￥{{item.jiahuaAmount || 0}}
                      <template
                        v-if="item.status !== 1 && item.isJiahuaCostModify === 1"
                      >
                        <a-icon
                          type="info-circle"
                          theme="twoTone"
                          @click="checkChange(item.orderTruckId)"
                        />
                      </template>
                    </span>
                    <orderOperate type="list" :item="item" @initPage="handleSubmit">
                      <a-button
                        ghost
                        type="primary"
                        v-if="isAssignDriver(item)"
                        @click="doAssign('ASSIGN', item.status, item.orderTruckId, item.dispatchType, (item.containerNo&&item.containerSealNo) ? 2 : 1)"
                        style="margin-left: 10px;"
                      >指派</a-button>
                      <a-button
                        ghost
                        type="primary"
                        v-if="isChangeDriver(item)"
                        @click="doAssign('RE_ASSIGN', item.status, item.orderTruckId, item.dispatchType, (item.containerNo&&item.containerSealNo) ? 2 : 1)"
                        style="margin-left: 10px;"
                      >改派</a-button>
                    </orderOperate>
                  </template>
                </a-card>
              </div>
            </a-checkbox-group>
          </template>
          <div
            v-if="tableData.length === 0"
            style="margin: 0 24px 24px; padding: 20px 0; background: white;"
          >
            <a-empty />
          </div>
          <!-- </a-spin> -->
          <p class="orderPagination">
            <a-pagination
              show-size-changer
              :current="pagination.current"
              :total="pagination.total"
              :showTotal="pagination.showTotal"
              :pageSize="pagination.pageSize"
              @showSizeChange="pagination.onShowSizeChange"
              @change="pagination.onChange"
            />
          </p>
        </a-col>
      </a-row>
    </a-spin>
    <!-- 派 -->
    <assign
      :visible="assignModal.visible"
      :type="assignModal.type"
      :order="assignModal.order"
      @setAssignVisible="setAssignVisible"
    ></assign>

    <!-- 历史记录 -->
    <a-modal :visible="visible" title="历史记录" @cancel="cancelSee" width="900px" :footer="null">
      <a-table :columns="columnsLocal" :data-source="detailData" rowKey="id" :pagination="false">
        <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import { mixin } from './common'
import assign from './assign'
import { Divider } from 'ant-design-vue'
import orderOperate from './orderOperations'
import { OrderOptions, SelfOperationOptions } from '../options'
import { queryTruckOrderList, receiveTruckOrder, queryTruckOrderCount, queryOrderTruckJiahuaBillHistory, queryTruckOrderWaitReceiveCount } from '@/api/landCenter'

const statusStr = ['', '待接单', '待派单', '司机待接单', '司机待出发', '运输中', '已完成', '已结算', '已作废']
const typeOptions = [
  { key: 'truckOrderCode', title: '公司编号' },
  { key: 'seagoingShipOrderCode', title: '运单号' },
  { key: 'containerSealNo', title: '封号' }
]

// 运输中 - status:5
const flowTypes = [
  { key: 11, title: '开始订单' },
  { key: 12, title: '送达门点' },
  { key: 13, title: '完成装卸' },
  { key: 14, title: '上传货运凭证' },
  { key: 16, title: '异常处理' }
]

// 已完成 - status:6
const opeTypes = [
  { key: 19, title: '完成订单-到港' },
  { key: 20, title: '套箱接单' },
  { key: 4, title: '异常结束' }
]
const costTypes = [
  { key: 1, title: '费用已录完' },
  { key: 0, title: '费用未录完' }
]

const defaultSearchForm = (status) => {
  return {
    status,
    belongCompany: '',
    custName: '',
    seagoingShipCompanyName: '', // 海船公司
    truckOrderCode: '', // 公司编号
    seagoingShipOrderCode: '', // 运单号
    goodsName: '',
    orderType: '',
    containerNo: '', // 箱号
    containerSealNo: '', // 封号
    startPortName: '', // 起运港
    endPortName: '', // 目的港
    address: '', // 发货地址
    arriveTime1: null, // 要求送达时间
    arriveTime2: null, // 要求送达时间
    dispatchReceiveTime: '',
    dispatchReceiveTime2: '',
    completeTime: '',
    completeTime2: '',
    isUrgent: '',
    isSelfOperation: '',
    truckNumber: '',
    isCostRecorded: '',
    driver: '',
    releaseStatus: '',
    shipNameAndVoyage: '',
    flowType: '', // 流程结点
    opeType: '', // 完成类型
    // 下拉词条，输入框暂存
    typexName: '',
    typeIndex: 'truckOrderCode',
    datexName: 1,
    dateData: null,
    time1: null,
    time2: null,
    word: '' // 1.2
  }
}

let timeout

export default {
  mixins: [mixin],
  data () {
    const columnsLocal =
      [
        {
          title: '操作时间',
          dataIndex: 'createTime',
          width: 170,
          customRender: (text, record, index) => {
            if (index === 0) {
              return <div>{text}<span class='redMsg'>最新记录</span></div>
            }
            return text
          }
        },
        {
          title: '操作人',
          dataIndex: 'operator'
        },
        {
          title: '动作类型',
          dataIndex: 'type',
          customRender: (text) => {
            if (text === 1) return '新增'
            else if (text === 2) return '编辑'
            return '--'
          }
        },
        {
          title: '费用类型',
          dataIndex: 'feeName'
        },
        {
          title: '金额',
          dataIndex: 'cnyAmount'
        },
        {
          title: '结算对象',
          dataIndex: 'custName'
        },
        {
          title: '备注',
          width: 150,
          ellipsis: true,
          dataIndex: 'remark'
        }
      ]

    return {
      activeKey: '',
      OrderOptions,
      SelfOperationOptions,
      typeOptions,
      costTypes,
      flowTypes,
      opeTypes,
      statusStr,
      spinning: false,
      searchForm: defaultSearchForm(''),
      time: [null, null],
      // 订单card start
      columns: [],
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      pagination: {},
      // 订单card end

      checkBox: {
        all: [],
        checked: []
      },
      listCount: {},

      // 派
      assignModal: {
        type: 'ASSIGN', // 'ASSIGN', 'RE_ASSIGN'
        visible: false,
        order: {}
      },
      visible: false,
      columnsLocal,
      detailData: [],
      needCount: 0,
      lastTime: null,
      // 待接单排序搜索
      value1: 0,
      value2: 1,
      value3: 1,
      // 已完成排序
      value4: '',
      sorts: {}
    }
  },
  components: {
    assign,
    orderOperate,
    [Divider.name]: Divider
  },
  methods: {
    orderTypeStr (key) {
      const t = this.OrderOptions.filter(v => v.key === key)[0]
      if (t) return t.title
      return '--'
    },
    getAddressType (item, id, addressType = 1) {
      const b = item.addressList.filter(v => v.portId === id && v.addressType === addressType)[0] // 1装货，2卸货，3提箱
      if (b) {
        let a = b.opeType
        return a === 1 ? '装货' : (a === 2 ? '卸货' : (a === 3 ? '提箱' : '空车'))
      }
      return ''
    },
    orderNum (count) {
      if (count && count > 999) count = '999+'
      return count ? `(${count})` : ''
    },
    onChangeStatus (key) {
      this.activeKey = key
      this.searchForm.typexName = ''
      this.time = [null, null]
      this.searchForm = defaultSearchForm(key)

      if (key === 6 || key === 7) {
        this.searchForm.datexName = 3 // 1.1
      }
      this.handleSubmit1()
    },
    initSearchCondition1 () {
      Object.assign(this.searchForm, {
        truckOrderCode: '', // 公司编号
        seagoingShipOrderCode: '', // 运单号
        containerSealNo: '' // 封号
      })
    },
    onChangeTypeOptions (value) {
      this.initSearchCondition1()
      this.searchForm[value] = this.searchForm.typexName
    },
    onNameChange (e) {
      this.searchForm.typexName = e.target.value
      this.onChangeTypeOptions(this.searchForm.typeIndex)
    },
    initSearchCondition2 () {
      Object.assign(this.searchForm, {
        dispatchReceiveTime: '',
        dispatchReceiveTime2: '',
        completeTime: '',
        completeTime2: '',
        arriveTime1: '',
        arriveTime2: ''
      })
    },
    onChangeDateOptions (value) {
      this.initSearchCondition2()
      if (value === 1) {
        this.searchForm.dispatchReceiveTime = this.searchForm.time1
        this.searchForm.dispatchReceiveTime2 = this.searchForm.time2
      } else if (value === 2) {
        this.searchForm.arriveTime1 = this.searchForm.time1
        this.searchForm.arriveTime2 = this.searchForm.time2
      } else if (value === 3) {
        this.searchForm.completeTime = this.searchForm.time1
        this.searchForm.completeTime2 = this.searchForm.time2
      }
    },
    onDateChange0 (date, dataStr) {
      this.searchForm.arriveTime1 = dataStr[0]
      this.searchForm.arriveTime2 = dataStr[1]
    },
    onDateChange (date, dataStr) {
      this.time = [date[0], date[1]]
      this.searchForm.time1 = dataStr[0]
      this.searchForm.time2 = dataStr[1]
      this.onChangeDateOptions(this.searchForm.datexName)
    },
    // 全选
    checkBoxCheck () {
      if (this.checkBox.checked.length !== this.checkBox.all.length) {
        // 全选
        this.checkBox.checked = [...this.checkBox.all]
      } else {
        // 取消
        this.checkBox.checked = []
      }
    },
    onChangeCheck (e) {
      const id = e.target.value
      const checked = e.target.checked
      let arr = this.checkBox.checked.filter(v => v !== id)
      if (checked) {
        arr.push(id)
      }
      this.checkBox.checked = arr
    },
    onCopy (e) {
      this.$message.success('地址已复制到剪切板')
    },
    addressInfo (addressList, index) {
      let info = {}
      if (addressList.length > 0) {
        if (index === 1) {
          info = addressList[0]
        } else if (index === 2 && addressList.length > 1) {
          info = addressList[1]
        }
      }
      if (info.opeType === 1) {
        info.opeType = '装货'
      } else if (info.opeType === 2) {
        info.opeType = '卸货'
      } else if (info.opeType === 3) {
        info.opeType = '提箱'
      }

      if (info.addressType === 1) {
        info.addressAll = info.portName
      } else if (info.addressType === 2) {
        info.addressAll = `${info.province}${info.city}${info.area}${info.address}`
      }
      return info
    },
    getPagination (data) {
      const pages = data ? data.pages : 0
      return {
        current: this.pageNum,
        pageSize: this.pageSize,
        total: data ? data.total : 0,
        showTotal: total => `共${total}条记录 第${this.pageNum}/${pages}页`,
        onChange: pageNum => {
          this.pageNum = pageNum
          this.handleSubmit()
        },
        onShowSizeChange: (current, size) => {
          this.pageNum = current
          this.pageSize = size
          this.handleSubmit()
        }
      }
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      if (this.searchForm.status === 1) { // 待接单tab下，计数重置
        this.needCount = 0
        clearTimeout(timeout)
        timeout = window.setTimeout(this.getNewestTruckOrderCount, 60000)
      }

      queryTruckOrderCount({}).then(rsp => {
        this.listCount = rsp.data
      })

      this.spinning = true
      this.checkBox.checked = []

      this.lastTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss') // 记录上次查询订单时间 1

      const t = {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }

      this.sorts = {}
      if (this.searchForm.status === 1) {
        this.sorts = {
          sort: this.value1 + this.value2,
          isUrgentSort: this.value3
        }
      } else if (this.searchForm.status === 6) {
        this.sorts = {
          sort: this.value4
        }
      }
      if (this.sorts && this.sorts.sort) {
        Object.assign(t, this.sorts)
      } else {
        this.value1 = 0
        this.value2 = 1
        this.value3 = 1
      }
      queryTruckOrderList(t).then(rsp => {
        this.spinning = false
        this.tableData = rsp.data.list
        this.checkBox.all = rsp.data.list.map(v => v.orderTruckId)
        this.pagination = this.getPagination(rsp.data)
      }).catch(() => { this.spinning = false })
    },
    /** ===================== 操作 =======================**/
    batchReceiveTruckOrder () {
      if (!this.$root._bc.receive) {
        this.$message.error('您无此权限！')
        return
      }
      let _t = this
      if (_t.checkBox.checked.length > 0) {
        _t.$confirm({
          title: '确定批量接单吗？',
          onOk () {
            receiveTruckOrder({ orderTruckIds: _t.checkBox.checked.join(',') }).then(rsp => {
              _t.$message.success('接单成功')
              _t.handleSubmit()
            })
          }
        })
      } else {
        _t.$message.error('请选择订单')
      }
    },
    batchAssignTruckOrder () { // 待派单才有
      if (!this.$root._bc.dispatch) {
        this.$message.error('您无此权限！')
        return
      }

      if (this.checkBox.checked.length > 0) {
        // 判断是否同类型箱子 - 空重
        let flag = 0
        this.checkBox.checked.map(id => {
          const temp = this.tableData.filter(v => v.orderTruckId === id)[0]
          if (temp) {
            flag += (temp.containerNo && temp.containerSealNo) ? 2 : 1
          }
        })

        let dispatchEmptyOrHeavyDef = 1
        if (flag !== this.checkBox.checked.length) {
          if (flag / 2 !== this.checkBox.checked.length) {
            this.$message.error('请选择箱态一致的订单进行指派')
            return false
          } else {
            dispatchEmptyOrHeavyDef = 2
          }
        } else {
          dispatchEmptyOrHeavyDef = 1
        }
        // console.log('dispatchEmptyOrHeavyDef', dispatchEmptyOrHeavyDef)

        this.doAssign('ASSIGN', 2, this.checkBox.checked.join(','), 1, dispatchEmptyOrHeavyDef)
      } else {
        this.$message.error('请选择订单')
      }
    },
    // 指派/改派/批量
    doAssign (type, status, orderTruckIds, dispatchType = 1, dispatchEmptyOrHeavy = 1) {
      if (!this.$root._bc.dispatch) {
        this.$message.error('您无此权限！')
        return
      }
      this.assignModal.type = type
      this.assignModal.order = {
        status,
        orderTruckIds,
        dispatchType,
        dispatchEmptyOrHeavy
      }
      this.assignModal.visible = true
    },
    setAssignVisible (v) {
      if (v) { // 保存成功
        this.handleSubmit()
      }
      this.assignModal.visible = false
    },
    // 详情
    gotoOrderDetail (id) {
      // this.$router.push(`orderDispatch/${id}`)
      window.open(`orderDispatch/${id}`, '_blank')
    },
    checkChange (orderTruckId) {
      queryOrderTruckJiahuaBillHistory({ orderTruckId }).then(rsp => {
        this.detailData = rsp.data
      })
      this.visible = true
    },
    cancelSee () {
      this.visible = false
      this.detailData = []
    },
    getNewestTruckOrderCount () {
      clearTimeout(timeout)
      queryTruckOrderWaitReceiveCount({ lastTime: this.lastTime }).then(rsp => {
        this.needCount = rsp.data ? rsp.data.waitReceiveCount : 0
        timeout = window.setTimeout(this.getNewestTruckOrderCount, 60000)
      })
    },
    isExportOrder (str) {
      return str && ~str.indexOf('_EXPORTS')
    },
    isImportOrder (str) {
      return str && ~str.indexOf('_IMPORTS')
    }
  },
  created () {
    this.pagination = this.getPagination()
  },
  mounted () {
    this.$nextTick(() => {
      this.handleSubmit()
      timeout = window.setTimeout(this.getNewestTruckOrderCount, 60000)
    })
  },
  beforeDestroy () {
    if (timeout) {
      clearTimeout(timeout)
    }
  }
}
</script>

<style lang="less" scoped>
.extraInfo {
  float: left;
  width: 340px;
  .xdan_time {
    color: rgb(182, 182, 182);
  }
}
.checkBoxStyle {
  float: left;
  height: 21px;
  display: block;
  line-height: 21px;
  padding-left: 5px;
}

.optRemarkClass {
  /deep/ .ant-descriptions-item-content {
    width: 88% !important;
    white-space: initial !important;
    text-overflow: -o-ellipsis-lastline;
    display: -webkit-box !important;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}

/deep/ td {
  position: relative;
  .redMsg {
    position: absolute;
    display: inline-block;
    background: red;
    top: 0;
    width: 60px;
    left: 0;
    font-size: 12px;
    height: 16px;
    text-align: center;
    color: white;
  }
}

.addressMain {
  display: inline-block;
  max-width: 60%;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-word;
  vertical-align: bottom;
  padding-right: 4px;
}
</style>
